﻿using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Security.Principal;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using System.Web.Security;
using volva.Models;
using volva.Services;

namespace volva.Controllers
{

    [HandleError]
    public class AccountController : Controller
    {
        public IFormsAuthenticationService FormsService { get; set; }
        public IMembershipService MembershipService { get; set; }

        protected override void Initialize(RequestContext requestContext)
        {
            if (FormsService == null) { FormsService = new FormsAuthenticationService(); }
            if (MembershipService == null) { MembershipService = new AccountMembershipService(); }

            base.Initialize(requestContext);
        }

        // **************************************
        // URL: /Account/LogOn
        // **************************************

        public ActionResult LogOn()
        {
            return View();
        }

        [HttpPost]
        public ActionResult LogOn(LogOnModel model, string returnUrl)
        {
            if (ModelState.IsValid)
            {
                if (MembershipService.ValidateUser(model.UserName, model.Password))
                {
                    FormsService.SignIn(model.UserName, model.RememberMe);
                    if (!String.IsNullOrEmpty(returnUrl))
                    {
                        return Redirect(returnUrl);
                    }
                    else
                    {
                        return RedirectToAction("Index", "Home");
                    }
                }
                else
                {
                    ModelState.AddModelError("", "Notendanafnið eða lykilorðið er vitlaust");
                }
            }

            // If we got this far, something failed, redisplay form
            return View(model);
        }

        // **************************************
        // URL: /Account/LogOff
        // **************************************

        public ActionResult LogOff()
        {
            FormsService.SignOut();
            
            return RedirectToAction("Index", "Home");
        }

        // **************************************
        // URL: /Account/Register
        // **************************************
        
        public ActionResult Register()
        {
            ViewData["PasswordLength"] = MembershipService.MinPasswordLength;
            return View();
        }

        [HttpPost]
        public ActionResult Register(RegisterModel model)
        {
            if (ModelState.IsValid)
            {
                // Attempt to register the user
                MembershipCreateStatus createStatus = MembershipService.CreateUser(model.UserName, model.Password, model.Email);

                if (createStatus == MembershipCreateStatus.Success)
                {
                    // BEGIN: Edited by the development team.
                    WebUser user = new WebUser();

                    user.username = model.UserName;
                    user.email = model.Email;
                    //user.nsfw = false;

                    AccountService.Register(user);
                    // END: Edited by the development team.
                    FormsService.SignIn(model.UserName, false /* createPersistentCookie */);
                    return RedirectToAction("Index", "Home");
                }
                else
                {
                    ModelState.AddModelError("", AccountValidation.ErrorCodeToString(createStatus));
                }
            }

            // If we got this far, something failed, redisplay form
            ViewData["PasswordLength"] = MembershipService.MinPasswordLength;
            return View(model);
        }

        // **************************************
        // URL: /Account/ChangePassword
        // **************************************

        [Authorize]
        public ActionResult ChangePassword()
        {
            ViewData["PasswordLength"] = MembershipService.MinPasswordLength;
            return View();
        }

        [Authorize]
        [HttpPost]
        public ActionResult ChangePassword(ChangePasswordModel model)
        {
            if (ModelState.IsValid)
            {
                if (MembershipService.ChangePassword(User.Identity.Name, model.OldPassword, model.NewPassword))
                {
                    return RedirectToAction("ChangePasswordSuccess");
                }
                else
                {
                    ModelState.AddModelError("", "The current password is incorrect or the new password is invalid.");
                }
            }

            // If we got this far, something failed, redisplay form
            ViewData["PasswordLength"] = MembershipService.MinPasswordLength;
            return View(model);
        }

        // **************************************
        // URL: /Account/ChangePasswordSuccess
        // **************************************

        public ActionResult ChangePasswordSuccess()
        {
            return View();
        }

        /*
         *  The following functions are added by the development team.
         *  The above functions were automaticlly genetrated.
         */

        /// <summary>
        /// The input page for changing a account.
        /// </summary>
        /// <returns>Returns the default view for the change account page</returns>
        public ActionResult ChangeAccount()
        {
            return View();
        }
        /*/// <summary>
        /// The change account page with the changed user data contained in POST
        /// </summary>
        /// <param name="model">The model containing the user data</param>
        /// <returns>A confirmation page</returns>
        public ActionResult ChangeAccount(WebUser model)
        {
            AccountService.ChangeAccount(model);
            return View();
        }*/
        /// <summary>
        /// Deletes a user
        /// </summary>
        /// <returns>A confirmation page for the user</returns>
        public ActionResult Delete()
        {
            return View();
        }
        /// <summary>
        /// The delete account logic 
        /// </summary>
        /// <param name="userId">The ID of the user that is to be deleted</param>
        /// <returns>A success or failure page</returns>
        public ActionResult Delete(int userId)
        {
            AccountService.DeleteAccount(userId);
            return View();
        }
        /// <summary>
        /// Adds a users role on a specific station
        /// </summary>
        /// <param name="userId">The ID of the user that will aquire the role on the station</param>
        /// <param name="stationId">The ID of the station that the user will get a role</param>
        /// <param name="role">The level of access the user will aquire</param>
        /// <returns>A confirmation site</returns>
        public ActionResult AddRole(WebUserRole userRole)
        {
            AccountService.AddRole(userRole);
            return View();
        }
        /// <summary>
        /// Removes a users role in a station
        /// </summary>
        /// <param name="userId">The ID of the user</param>
        /// <param name="stationId">The ID of the station</param>
        /// <param name="role">The access level of the user on the station</param>
        /// <returns>A confirmation page</returns>
        public ActionResult RemoveRole(WebUserRole userRole)
        {
            AccountService.RemoveRole(userRole);
            return View();
        }
        /// <summary>
        /// Reads a specific message
        /// </summary>
        /// <param name="messageId">The ID of the message</param>
        /// <returns>A page where the user can read the message</returns>
        public ActionResult ReadMessage(int messageId)
        {
            MessageService.GetMessage(messageId);
            return View();
        }
        /// <summary>
        /// Enables the user to write a message
        /// </summary>
        /// <returns>A page where the user can input his message</returns>
        [HttpGet]
        public ActionResult WriteMessage()
        {
            return View();
        }
        /*public ActionResult WriteMessage(int id)
        {
            ViewData["user"] = AccountService.GetUserByID(id);
            return View();
        }*/
        /// <summary>
        /// List the users inbox
        /// </summary>
        /// <param name="userId">The user ID for the user that owns the messages</param>
        /// <returns>A page populated by the users messages</returns>
        [Authorize]
        public ActionResult Messages()
        {
            ViewData["Messages"] = MessageService.GetMessages(AccountService.GetUserIDByName(User.Identity.Name));

            return View();
        }

        /// <summary>
        /// Deletes a message from the inbox
        /// </summary>
        /// <param name="messageId">The ID of the message</param>
        /// <returns>A confirmation page</returns>
        [Authorize]
        public ActionResult DeleteMessage(int messageId)
        {
            Message message = MessageService.GetMessage(messageId);
            MessageService.Delete(message);
            return View();
        }
        /// <summary>
        /// Views a message
        /// </summary>
        /// <param name="id">The ID of the message to display</param>
        /// <returns>A page with the message displayed</returns>
        [Authorize]
        public ActionResult ViewMessage(int id)
        {
            Message message = MessageService.GetMessage(id);
            MessageService.MarkMessageAsRead(id);

            ViewData["message"] = message;
            return View();
        }
        /// <summary>
        /// Shows a user's public profile
        /// </summary>
        /// <param name="id">The ID of the user</param>
        /// <returns>A profile page for the user</returns>
        public ActionResult Profile(int id)
        {
            ViewData["user"] = AccountService.GetUserByID(id);
            ViewData["stations"] = StationService.GetStationsWhereAdminIs(id);
            return View();
        }
        public ActionResult SendMessage()
        {
            if (Request.Form["WebUserTo"] != null)
            {
                Message message = new Message
                {
                    WebUser_from_id = AccountService.GetUserIDByName(User.Identity.Name),
                    WebUser_to_id = AccountService.GetUserIDByName(Request.Form["WebUserTo"]),
                    body = Request.Form["body"],
                    subject = Request.Form["subject"],
                    isNew = true
                };

                MessageService.Send(message);
            }

            return View();
        }
        /*
        /// <summary>
        /// Sends a message to a user if he exists
        /// </summary>
        /// <param name="model">The model of the message</param>
        /// <returns>A confirmation page</returns>
        [HttpPost]
        public ActionResult WriteMessage(FormCollection form)
        {
            Message message = new Message
            {
                WebUser_to_id = AccountService.GetUserIDByName(form["WebUserTo"]),
                body = form["body"],
                subject = form["subject"],
                isNew = true,
                WebUser_from_id = AccountService.GetUserIDByName(User.Identity.Name)
            };
            MessageService.Send(message);
            return View();
        }*/
        public ActionResult Settings()
        {
            ViewData["user"] = AccountService.GetUserByID(AccountService.GetUserIDByName(User.Identity.Name));
            return View();
        }
        [HttpPost]
        public ActionResult Settings(WebUser model)
        {
            WebUser loggedInUser = AccountService.GetUserByID(AccountService.GetUserIDByName(User.Identity.Name));
            ViewData["message"] = "Stillingum var breytt.<br />";
            ViewData["user"] = loggedInUser;
            
            if(model.areaCode.Length > 3)
            {
                ViewData["message"] = "Póstfangið má ekki vera lengri en þrír stafir.";
                return View();
            }

            AccountService.ChangeAccount(model, AccountService.GetUserIDByName(User.Identity.Name));
            return Redirect("/Home/Index/");
            //return View();
        }
    }
}
